import 'react-big-calendar/lib/css/react-big-calendar.css'
import React, {useCallback, useState} from 'react'
import {makeStyles} from '@material-ui/core/styles';
import api from "./api";
import dayjs from "dayjs";
import Button from "@material-ui/core/Button";
import {Calendar, dayjsLocalizer} from "react-big-calendar";
import Dialog from "@material-ui/core/Dialog";
import DialogContent from "@material-ui/core/DialogContent";
import TextField from "@material-ui/core/TextField";
import DialogActions from "@material-ui/core/DialogActions";
import {getEndOfMonth, getStartOfMonth} from './utils/dateUtils'
import message from "./utils/message"
import constants from "./utils/constants"

const useStyles = makeStyles(() => ({
    app: {
        width: '90vw',
        height: '90vh'
    },
    top: {
        paddingBottom: '10PX'
    },
    dialogPaper: {
        minHeight: '50vh',
        minWidth: '25vw'
    }
}));
export default function App() {
    const classes = useStyles();
    const [myEventsList, setMyEventsList] = useState([])
    const [open, setOpen] = useState(false)
    const localize = dayjsLocalizer(dayjs)
    const [formData, setFormData] = useState({});
    const [start, setStart] = useState(dayjs(getStartOfMonth()).format(constants.SHORT_DATE_STR))
    const [end, setEnd] = useState(dayjs(getEndOfMonth()).format(constants.SHORT_DATE_STR))
    const [showDel, setShowDel] = useState(true)
    /**
     * 根据时间范围查询事件
     * @type {(function(): void)|*}
     */
    const init = useCallback(() => {
        api.myEvent.list({url:start+"/"+end}).then(
            resp => {
                const list = resp.entity;
                list.forEach((item) => {
                    item.start = dayjs(item.start,constants.LOG_DATE_STR).toDate();
                    item.end = dayjs(item.end,constants.LOG_DATE_STR).toDate();
                })
                setMyEventsList(list)
            }
        ).catch(

        )
    }, [start, end])

    React.useEffect(() => {
        init();
    }, [init])

    /**
     * 新增事件弹窗
     */
    function handleClickOpen() {
        setFormData({
            id: "",
            title: "",
            start: new Date(),
            end: new Date()
        })
        setShowDel(false)
        setOpen(true)
    }

    /**
     * 关闭事件弹窗
     */
    function handleClose() {
        setOpen(false)
    }

    /**
     * 选择事件弹窗
     * @param slotInfo
     */
    function handleSelect(slotInfo) {
        setFormData({
            id: slotInfo.id,
            title: slotInfo.title,
            start: slotInfo.start,
            end: slotInfo.end
        })
        setShowDel(true)
        setOpen(true)
    }

    /**
     * 切换视图
     * @param slotInfo
     * @param type
     */
    function handleRangeChange(slotInfo, type) {
        let start;
        let end;
        if (type === "month" || type === "agenda") {
            start = dayjs(slotInfo.start).format(constants.SHORT_DATE_STR)
            end = dayjs(slotInfo.end).format(constants.SHORT_DATE_STR)
        } else if (type === "week") {
            start = dayjs(slotInfo[0]).format(constants.SHORT_DATE_STR)
            end = dayjs(slotInfo[6]).format(constants.SHORT_DATE_STR)
        } else if (type === "day") {
            start = dayjs(slotInfo[0]).format(constants.SHORT_DATE_STR)
            end = dayjs(slotInfo[0]).format(constants.SHORT_DATE_STR)
        } else {
            return;
        }
        setStart(start)
        setEnd(end)
        init()
    }

    /**
     * 切换导航
     * @param slotInfo
     */
    function handleNavigate(slotInfo) {
        let date = dayjs(slotInfo).format(constants.SHORT_DATE_STR);
        setStart(date)
        setEnd(date)
        init()
    }

    /**
     * 修改表单数据
     * @param e
     */
    function changeFormData(e) {
        setFormData({...formData, [e.target.name]:  e.target.value})
    }

    /**
     * 检验表单数据
     * @returns {string}
     */
    function verifyFormData() {
        let err = "";
        if (formData.title === "") {
            err = "标题不能为空";
        }
        if (formData.start === "") {
            err = "开始时间不能为空";
        }
        if (formData.end === "") {
            err = "结束时间不能为空";
        }
        return err;
    }

    /**
     * 保存事件
     */
    function save() {
        let err = verifyFormData();
        let data={...formData, start: dayjs(formData.start).format(constants.LOG_DATE_STR),end: dayjs(formData.end).format(constants.LOG_DATE_STR)}
        if (err === "") {
            if (formData.id === "") {
                api.myEvent.post(data).then(() => {
                    message.success({content: "保存成功", duration: 2000})
                    setOpen(false)
                    init()
                }).catch(() => {
                    message.error({content: "保存失败", duration: 2000})
                });
            } else {
                api.myEvent.put(data).then(() => {
                    message.success({content: "保存成功", duration: 2000})
                    setOpen(false)
                    init()
                }).catch(() => {
                    message.error({content: "保存失败", duration: 2000})
                });
            }
        } else {
            message.error({content: err, duration: 2000})
        }

    }

    /**
     * 删除事件
     */
    function del() {
        api.myEvent.del({url: formData.id}).then(() => {
            message.success({content: "删除成功", duration: 2000})
            setOpen(false)
            init()
        }).catch(() => {
            message.error({content: "删除失败", duration: 2000})
        })

    }

    return (
        <div className={classes.app}>
            <div className={classes.top}>
                <Button variant="contained" color="primary" onClick={handleClickOpen}>
                    添加
                </Button>
            </div>
            <Calendar
                localizer={localize}
                events={myEventsList}
                dateFormat="YYYY-MM-DD HH:mm"
                defaultView="month"
                onSelectEvent={handleSelect}
                onNavigate={handleNavigate}
                onRangeChange={handleRangeChange}
            />
            <div>
                <Dialog
                    classes={{paper: classes.dialogPaper}}
                    open={open}
                    onClose={handleClose}>
                    <DialogContent>
                        <div>
                            <TextField
                                id="standard-full-width"
                                name="title"
                                label="标题"
                                placeholder="Placeholder"
                                value={formData.title}
                                margin="normal"
                                onChange={changeFormData}
                            />
                        </div>
                        <div>
                            <TextField
                                id="datetime-local"
                                name="start"
                                value={dayjs(formData.start).format(constants.ISO_DATE_STR)}
                                fullWidth
                                label="开始时间"
                                type="datetime-local"
                                onChange={changeFormData}
                                InputLabelProps={{
                                    shrink: true,
                                }}/>
                        </div>
                        <div>
                            <TextField
                                id="datetime-local"
                                fullWidth
                                name="end"
                                value={dayjs(formData.end).format(constants.ISO_DATE_STR)}
                                label="结束时间"
                                type="datetime-local"
                                onChange={changeFormData}
                                InputLabelProps={{
                                    shrink: true,
                                }}/>
                        </div>
                    </DialogContent>
                    <DialogActions>
                        <Button onClick={save} color="primary">
                            SAVE
                        </Button>
                        {showDel ?
                            <Button onClick={del} color="primary">
                                DELETE
                            </Button>
                            : null
                        }
                        <Button onClick={handleClose} color="primary">
                            CANCEL
                        </Button>
                    </DialogActions>
                </Dialog>
            </div>
        </div>
    );
}
